package com.es.disped.core.shiro;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;


/**
 * @author Anson<br>
 *	Copyright by EasyShare 2019<br>
 *  
 *  All right reserved<br>
 *
 *  Created on 2019年6月28日 上午10:03:45<br>
 *  名称：ShrioAuthenticationFilter.java<br>
 *  描述：重写Form过滤器，针对跨域请求不拦截OPTIONS方法<br>
 */
public class ShrioAuthenticationFilter extends FormAuthenticationFilter {

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		if (request instanceof HttpServletRequest) {
            if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")
//            		||((HttpServletRequest) request).getMethod().toUpperCase().equals("GET")
//            		||((HttpServletRequest) request).getMethod().toUpperCase().equals("POST")
            		) {
                return true;
            }
        }
        return super.isAccessAllowed(request, response, mappedValue);
	}
	
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
//		HttpServletResponse httpResponse = (HttpServletResponse) response;
//        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
//        httpResponse.setHeader("Access-Control-Allow-Origin", ((HttpServletRequest)request).getHeader("Origin"));
        return false;
	}
	
//	@Override
//	public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain)
//			throws ServletException, IOException {
////		HttpServletResponse res = (HttpServletResponse) response;
////
////        res.setContentType("application/json;charset=UTF-8");
////
////        res.setHeader("Access-Control-Allow-Origin", "*");
////
////        res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
////
////        res.setHeader("Access-Control-Max-Age", "3600");
////
////        res.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
////
////        res.setHeader("Access-Control-Allow-Credentials", "true");
////
////        res.setHeader("XDomainRequestAllowed","1");
//
//        chain.doFilter(request, response);
//	}
}
